package com.movies.service.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Ticket;
import com.movies.service.entity.User;
import com.movies.service.service.TicketService;
import com.movies.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;


@RestController
@RequestMapping("/user/ticket")
@SaCheckLogin
public class UserTicketController {

    @Autowired
    private TicketService ticketService;
    @Autowired
    private UserService userService;

//    分页查询当前用户的订单（可按状态筛选）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) String status) {
        Long uid = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<Ticket> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Ticket::getUid, uid)
                .eq(status != null && !status.isEmpty(), Ticket::getStatus, status);
        Page<Ticket> page = ticketService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success(page);
    }


//    获取个人订单信息
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        Long uid = StpUtil.getLoginIdAsLong();
        Ticket t = ticketService.getById(id);
        if (t == null || !uid.equals(t.getUid())) {
            return Result.error(Constants.CODE_401, "无权查看该订单");
        }
        return Result.success(t);
    }


//    创建订单（默认未支付）
    @PostMapping
    public Result create(@RequestBody CreateTicketReq req) {
        Long uid = StpUtil.getLoginIdAsLong();
        User user = (User) StpUtil.getSession().get("user");
        if (user == null) {
            user = userService.getById(uid);
        }
        Ticket t = new Ticket();
        t.setUid(uid);
        t.setUname(user != null ? user.getUname() : null);
        t.setMid(req.getMid());
        t.setMname(req.getMname());
        t.setPrice(req.getPrice());
        t.setQuantity(req.getQuantity() != null ? req.getQuantity() : 1);
        t.setStatus("UNPAID");
        t.setNote(req.getNote());
        boolean ok = ticketService.save(t);
        return ok ? Result.success("创建成功", t) : Result.error(Constants.CODE_600, "创建失败");
    }


//    购票（扣减余额并创建已支付订单）
    @PostMapping("/buy")
    public Result buy(@RequestBody BuyTicketReq req) {
        Long uid = StpUtil.getLoginIdAsLong();
        User user = (User) StpUtil.getSession().get("user");
        if (user == null) {
            user = userService.getById(uid);
        }
        if (user == null) {
            return Result.error(Constants.CODE_600, "用户不存在");
        }
        int qty = req.getQuantity() != null ? req.getQuantity() : 1;
        if (qty <= 0) qty = 1;
        BigDecimal unit = req.getUnitPrice() != null ? req.getUnitPrice() : BigDecimal.ZERO;
        BigDecimal total = unit.multiply(BigDecimal.valueOf(qty));
        if (user.getBalance() == null) user.setBalance(BigDecimal.ZERO);
        if (user.getBalance().compareTo(total) < 0) {
            return Result.error(Constants.CODE_600, "余额不足，请先充值");
        }
        // 扣减余额
        user.setBalance(user.getBalance().subtract(total));
        boolean userOk = userService.updateById(user);
        if (!userOk) {
            return Result.error(Constants.CODE_600, "扣款失败，请稍后重试");
        }
        // 创建已支付订单
        Ticket t = new Ticket();
        t.setUid(uid);
        t.setUname(user.getUname());
        t.setMid(req.getMid());
        t.setMname(req.getMname());
        t.setPrice(total);
        t.setQuantity(qty);
        t.setStatus("PAID");
        t.setNote(req.getNote());
        boolean ok = ticketService.save(t);
        return ok ? Result.success("购票成功", t) : Result.error(Constants.CODE_600, "购票失败");
    }


//    修改个人订单信息
    @PutMapping
    public Result update(@RequestBody UpdateTicketReq req) {
        Long uid = StpUtil.getLoginIdAsLong();
        Ticket t = ticketService.getById(req.getId());
        if (t == null || !uid.equals(t.getUid())) {
            return Result.error(Constants.CODE_401, "无权操作该订单");
        }
        if (req.getStatus() != null) {
            t.setStatus(req.getStatus());
        }
        t.setNote(req.getNote());
        boolean ok = ticketService.updateById(t);
        return ok ? Result.success("更新成功") : Result.error(Constants.CODE_600, "更新失败");
    }

//  删除个人订单信息
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        Long uid = StpUtil.getLoginIdAsLong();
        Ticket t = ticketService.getById(id);
        if (t == null || !uid.equals(t.getUid())) {
            return Result.error(Constants.CODE_401, "无权操作该订单");
        }
        boolean ok = ticketService.removeById(id);
        return ok ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

    // 创建订单请求体
    public static class CreateTicketReq {
        private Long mid;
        private String mname;
        private BigDecimal price;
        private Integer quantity;
        private String note; // 富文本备注
        public Long getMid() { return mid; }
        public void setMid(Long mid) { this.mid = mid; }
        public String getMname() { return mname; }
        public void setMname(String mname) { this.mname = mname; }
        public BigDecimal getPrice() { return price; }
        public void setPrice(BigDecimal price) { this.price = price; }
        public Integer getQuantity() { return quantity; }
        public void setQuantity(Integer quantity) { this.quantity = quantity; }
        public String getNote() { return note; }
        public void setNote(String note) { this.note = note; }
    }

    // 购票请求体（包含单价与数量）
    public static class BuyTicketReq {
        private Long mid;
        private String mname;
        private BigDecimal unitPrice; // 单价
        private Integer quantity;     // 购买数量
        private String note;          // 备注
        public Long getMid() { return mid; }
        public void setMid(Long mid) { this.mid = mid; }
        public String getMname() { return mname; }
        public void setMname(String mname) { this.mname = mname; }
        public BigDecimal getUnitPrice() { return unitPrice; }
        public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; }
        public Integer getQuantity() { return quantity; }
        public void setQuantity(Integer quantity) { this.quantity = quantity; }
        public String getNote() { return note; }
        public void setNote(String note) { this.note = note; }
    }

    // 更新订单请求体
    public static class UpdateTicketReq {
        private Long id;
        private String status; // PAID/UNPAID
        private String note;   // 富文本备注
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public String getNote() { return note; }
        public void setNote(String note) { this.note = note; }
    }
}
